import React, {
  createRef,
} from "react";
import {
  Space,
  Row,
  Table,
  Pagination,
  Typography,
  Button,
  message,
  Form,
  Input,
  Modal,
} from "antd";
import "./index.less";
import { listLabel, createLabel } from "@/services/label";

const { TextArea } = Input;

class Label extends React.Component {
   // 表格规则定义
   columns = [
     {
       title: "标签名称",
       dataIndex: "labName",
     },
     {
       title: "选项",
       dataIndex: "labOption",
       //   render: (text, record) => (
       //       Text.join(',')
       //   )
     },
     {
       title: "操作",
       render: (text, record) => (
         <Space size="middle">
           <a onClick={this.editLabel.bind(this, record)}>编辑</a>
           <a onClick={this.deleteAlert.bind(this, record)}>删除</a>
         </Space>
       ),
     },
   ];

   // 表格
  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        selectedRows,
      });
    },
    getCheckboxProps: (record) => ({
      name: record.name,
    }),
  };

  constructor(props) {
    super(props);

    this.state = {
      total: 0,
      currentPage: 1,
      size: 10,
      dataSource: [],
      query: 0,
      labelFormModalVisible: false,
      make: '',
      makeMessage: '',
      selectedRows: [],
      deleteFormModalVisible: false,
      deleteData: [],
    };

    this.searchFormRef = createRef();
    this.LabelFormRef = createRef();
    this.tableWrapperRef = createRef();
    this.otherHeight = 0;
  }

  // 加载table
  componentDidMount() {
    this.fetchTableData()
  }

  // 页码改变时
  handlePageChange = (page, size) => {
    this.setState({ currentPage: page, size }, this.fetchTableData);
  };

  // 新建弹窗开关
  createLabel = () => {
    this.setState({
      labelFormModalVisible: true,
      make: "新建标签",
      makeMessage: "创建",
    });
    setTimeout(() => {
      const { setFieldsValue } = this.LabelFormRef.current;
      setFieldsValue({
        labName: null,
        labOption: null
      });
    }, 100);
  };

  // 编辑弹窗开关
  editLabel = (a) => {
    this.setState({
      labelFormModalVisible: true,
      make: "编辑标签",
      makeMessage: "修改",
    });
    // 报错：TypeError: Cannot read property ‘setFieldsValue’ of null
    // 原因：对话框模块还没显示，也就是表单还没挂载就调用了setFieldsValue，所以报错
    // 设置定时器延迟解决
    setTimeout(() => {
      const { setFieldsValue } = this.LabelFormRef.current;
      setFieldsValue({
        labName: a.labName,
        labOption: a.labOption.replace(/，/g, "\n")
      });
    }, 100);
  };

  // 控制删除弹窗
deleteAlert = (a) => {
  const { selectedRows } = this.state;
  if (a) {
    this.setState({
      deleteData: a,
      deleteFormModalVisible: true,
    });
  } else if (selectedRows.length !== 0) {
    this.setState({
      deleteData: selectedRows,
      deleteFormModalVisible: true,
    });
  } else {
    message.error("未选中删除信息");
  }
};

  // 向服务器提供删除请求
  deleteLabels = () => {
    const { deleteData } = this.state;
    // 新建服务器函数，暂放
    createLabel({
      data: { deleteData },
    }).then((Res) => {
      if (Res.data.ret === 0) {
        // 删除成功
        message.success("删除成功！");
        // 关闭弹窗
        this.setState({
          deleteFormModalVisible: false,
        });
        this.fetchTableData();
      } else {
        // 删除失败
        message.success("删除失败");
      }
    });
  };

  // 重置对应输入框
  resetFliter = () => {
    const { resetFields } = this.searchFormRef.current;
    resetFields();
  };

  // 查询对应函数
  search = () => {
    this.fetchTableData();
  };

  // 获取输入框信息
  getSearchFormValue = () => {
    const { getFieldsValue } = this.searchFormRef.current;
    const { labName } = getFieldsValue();
    return { labName };
  };

  // 获取表格中部分信息,编辑功能中使用
  getLabelFormValue = () => {
    const { getFieldsValue } = this.LabelFormRef.current;
    const { labName, labOption, id } = getFieldsValue();
    return { labName, labOption, id };
  };

  // 新建/编辑账户发送服务端请求
  handleSaveLabelInfo = () => {
    const { labName, labOption, id } = this.getLabelFormValue();
    createLabel({
      labName,
      labOption: labOption + ''.split('\n'),
      id
    }).then((Res) => {
      const { makeMessage } = this.state;
      if (Res.data.ret === 0) {
        message.success(`${makeMessage}成功！`);
        this.setState({
          // 关闭新建弹窗
          labelFormModalVisible: false,
        });
      } else {
        message.error(`${makeMessage}失败`);
      }
    });
  };

  // 刷新数据
  fetchTableData = async () => {
    const { size, currentPage } = this.state;
    const { labName } = this.getSearchFormValue();

    const {
      data: { ret },
      data: {
        data: { list, total, query },
      },
    } = await listLabel({
      size,
      page: currentPage,
      labName
    });

    if (ret !== 0) {
      return;
    }
    this.setState({ total, dataSource: list, query });
  };

  // 编辑/新建弹窗样式
  renderLabelFormModal = () => {
    const { make, labelFormModalVisible } = this.state;
    return (
      <Modal
        centered
        title={make}
        visible={labelFormModalVisible}
        onOk={() => this.handleSaveLabelInfo()}
        onCancel={() => this.setState({ labelFormModalVisible: false })}
      >
        <Form
          ref={this.LabelFormRef}
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
        >
          <Form.Item
            name="labName"
            label="标签名称："
            rules={[{ required: true, message: "请输入标签名称" }]}
          >
            <Input
              placeholder="请输入标签名称"
              style={{ width: 200 }}
            />
          </Form.Item>
          {/* <p className="formTip">输入选项值（每行一个）</p> */}
          <Form.Item
            name="labOption"
            label="标签选项："
            rules={[{ required: true, message: "请输入标签选项" }]}
            extra="输入选项值（每行一个）"
          >
            {/* <p className="formTip">输入选项值（每行一个）</p> */}
            <TextArea
              autosize={{ minRows: 2, maxRows: 4 }}
              style={{ width: 200 }}
              placeholder="请输入标签选项"
            />
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  // 打开删除弹窗
  showModal = () => {
    this.setState({
      deleteFormModalVisible: true,
    });
  };

  // 关闭删除弹窗
  hideModal = () => {
    this.setState({
      deleteFormModalVisible: false,
    });
  };

  // 删除弹窗样式
  deleteLabelFormModal = () => {
    const { deleteFormModalVisible } = this.state
    return (
      <Modal
        title="重要提醒"
        visible={deleteFormModalVisible}
        onOk={this.deleteLabels}
        onCancel={this.hideModal}
        okText="确认"
        cancelText="取消"
      >
        <p>您正在删除当前选中的内容，删除后，已使用该标签的产品不受影响，您确认吗？</p>
      </Modal>
    )
  };

  render() {
    const {
      total, dataSource, currentPage, size, query
    } = this.state;
    return (
      <div className="Adminer">
        <div className="AdminerSearch">
          <div className="AdminerTitle">
            <h2>
              标签管理
              <div className="blank" />
            </h2>
          </div>
          <Form ref={this.searchFormRef}>
            <Form.Item label="标签名称：" name="labName" className="account">
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item className="return">
              <Button type="ghost" onClick={() => this.resetFliter()}>
                重置
              </Button>
            </Form.Item>
            <Form.Item className="search">
              <Button type="primary" onClick={() => this.search()}>
                查询
              </Button>
            </Form.Item>
          </Form>
        </div>

        <div className="AdminerList">
          <p>标签列表</p>
          <Form>
            <Form.Item className="AllDelete">
              <Button type="ghost" onClick={() => this.deleteAlert()}>
                批量删除
              </Button>
            </Form.Item>
            <Form.Item className="add">
              <Button type="primary" onClick={() => this.createLabel()}>
                +新建
              </Button>
            </Form.Item>
          </Form>
          <Table
            rowSelection={this.rowSelection}
            pagination={false}
            // loading={!isReady}
            columns={this.columns}
            dataSource={dataSource}
          />
          <Row justify="space-between" align="middle">
            <Typography.Text>
              共
              {query}
              条记录 第
              {currentPage}
              /
              {' '}
              {Math.ceil(query / size) || 1}
              页
            </Typography.Text>

            <Pagination
              showQuickJumper
              showLessItems
              total={total}
              pageSize={10}
              current={currentPage}
              showSizeChanger={false}
              onChange={this.handlePageChange}
            />
          </Row>
        </div>
        {this.renderLabelFormModal()}
        {this.deleteLabelFormModal()}
      </div>
    );
  }
}
export default Label;
